import { push, replace, go, goBack } from "react-router-redux";
import qs from "query-string";
export default class H5NavAdapter {
  constructor(store) {
    this.store = store;
    this.historyRouters = [];
    var url = {
      pathname: this._getNav().location.pathname,
      search: ""
    };
    this.historyRouters.push(url);
  }

  replace(routeName, params) {
    var searchString = "";
    if (params) {
      searchString = "?" + qs.stringify(params);
    }
    var url = { pathname: routeName, search: searchString };
    this.historyRouters.splice(this.historyRouters.length - 1, 1, url);
    this.store.dispatch(replace(url));
  }

  push(routeName, params) {
    var searchString = "";
    if (params) {
      searchString = "?" + qs.stringify(params);
    }
    var url = { pathname: routeName, search: searchString };
    this.historyRouters.push(url);
    this.store.dispatch(push(url));
  }

  goBack() {
    this.historyRouters.pop();
    this.store.dispatch(goBack());
  }

  go(delta) {
    let startIndex = this.historyRouters.length + delta;
    this.historyRouters.splice(startIndex, Math.abs(delta));
    this.store.dispatch(go(delta));
  }

  backTo(routeName) {
    return new Promise((resolve, reject) => {
      for (var key in this.historyRouters) {
        var routerName = this.historyRouters[key].pathname;

        let index = routerName && routerName.indexOf(routeName);
        if (index > -1) {
          let backtoIndex = this.historyRouters.length - key - 1;
          let startIndex = this.historyRouters.length - backtoIndex;
          this.historyRouters.splice(startIndex, Math.abs(-backtoIndex));
          this.store.dispatch(go(-backtoIndex));
          resolve();
          return;
        }
      }
      reject(new Error(`找不到${routeName}对应的路由`));
    });
  }
  getParams(key) {
    var nav = this._getNav();
    var search = nav.location.search;
    if (!search) {
      return;
    }
    var params = qs.parse(search.split("?")[1]);
    if (!key) {
      return params;
    }
    return params && params[key];
  }

  goHome() {
    this.store.dispatch(replace("/"));
    this.historyRouters = [];
    var url = {
      pathname: "/",
      search: ""
    };
    this.historyRouters.push(url);
  }
  _getNav() {
    var nav = this.store.getState().router;
    return nav;
  }
}
